package com.hghivln.controller.doctor;

import com.hghivln.aspectj.annotation.Log;
import com.hghivln.aspectj.enums.BusinessType;
import com.hghivln.config.pay.AlipayConfig;
import com.hghivln.config.pay.PayService;
import com.hghivln.constants.Constants;
import com.hghivln.pojo.domain.OrderCharge;
import com.hghivln.pojo.dto.OrderChargeDto;
import com.hghivln.pojo.dto.OrderChargeFromDto;
import com.hghivln.pojo.dto.OrderChargeItemDto;
import com.hghivln.pojo.vo.AjaxResult;
import com.hghivln.service.OrderChargeService;
import com.hghivln.utils.ShiroUtils;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处方收费
 */
@RestController
@RequestMapping("doctor/charge")
public class ChargeController {

    @Reference
    private OrderChargeService orderChargeService;

    /**
     * 根据挂号ID查询未支付的处方信息及详情
     */
    @GetMapping("getNoChargeCareHistoryByRegId/{regId}")
    @HystrixCommand
    public AjaxResult getNoChargeCareHistoryByRegId(@PathVariable @Validated @NotBlank(message = "挂号单号不能为空") String regId) {
        return orderChargeService.getNoChargeCareHistoryByRegId(regId);
    }

    /**
     * 创建现金收费订单
     */
    @PostMapping("createOrderChargeWithCash")
    @HystrixCommand
    @Log(title = "创建现金收费订单", businessType = BusinessType.INSERT)
    public AjaxResult createOrderChargeWithCash(@RequestBody @Validated OrderChargeFromDto orderChargeFromDto) {
        orderChargeFromDto.setSimpleUser(ShiroUtils.getCurrentSimpleUser());
        // 保存订单和订单详情
        String orderId = orderChargeService.saveOrderAndItems(orderChargeFromDto);
        // 支付成功回调
        return orderChargeService.paySuccess(orderId, Constants.PAY_TYPE_0, null);
    }

    /**
     * 创建支付宝支付订单
     * 根据订单ID返回订单支付地址和总金额
     */
    @PostMapping("createOrderChargeWithZfb")
    @HystrixCommand(commandProperties = { // 由于服务的响应超过1秒，会报超时错误，所以修改响应超时的时间
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
    })
    @Log(title = "创建支付宝支付订单", businessType = BusinessType.INSERT)
    public AjaxResult createOrderChargeWithZfb(@RequestBody @Validated OrderChargeFromDto orderChargeFromDto) {
        orderChargeFromDto.setSimpleUser(ShiroUtils.getCurrentSimpleUser());
        // 保存订单和订单详情
        String orderId = orderChargeService.saveOrderAndItems(orderChargeFromDto);

        String outTradeNo = orderId;
        String subject = "医疗管理系统支付平台";
        String totalAmount = orderChargeFromDto.getOrderChargeDto().getOrderAmount().toString();
        StringBuilder body = new StringBuilder();
        String undiscountableAmount = null;
        List<OrderChargeItemDto> orderChargeItemDtoList = orderChargeFromDto.getOrderChargeItemDtoList();
        for (OrderChargeItemDto orderChargeItemDto : orderChargeItemDtoList) {
            body.append(orderChargeItemDto.getItemName()).append("-").append(orderChargeItemDto.getItemPrice()).append(" ");
        }
        String notyifyUrl = AlipayConfig.notyifyUrl + outTradeNo;
        // 因为是支付宝支付，所以我们要返回给页面一个二维码
        Map<String, Object> pay = PayService.pay(outTradeNo, subject, totalAmount, undiscountableAmount, body.toString(), notyifyUrl);
        String qrCode = pay.get("qrCode").toString();
        if (StringUtils.isNotBlank(qrCode)) {
            // 创建支付成功
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId", outTradeNo);
            map.put("allAmount", totalAmount);
            map.put("payUrl", qrCode);
            return AjaxResult.success(map);
        } else {
            return AjaxResult.fail(pay.get("msg").toString());
        }
    }

    /**
     * 根据订单ID查询订单信息【验证是否支付成功】
     */
    @GetMapping("queryOrderChargeOrderId/{orderId}")
    @HystrixCommand
    public AjaxResult queryOrderChargeOrderId(@PathVariable @Validated @NotBlank(message = "收费ID不能为空") String orderId) {
        OrderCharge orderCharge = orderChargeService.queryOrderChargeByOrderId(orderId);
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("【" + orderId + "】订单号所在的订单不存在，请核对后再输入");
        } else {
            return AjaxResult.success(orderCharge);
        }
    }

    /**
     * 分页查询所有的订单
     */
    @GetMapping("queryAllOrderChargeForPage")
    @HystrixCommand
    public AjaxResult queryAllOrderChargeForPage(OrderChargeDto orderChargeDto) {
        return orderChargeService.selectAllOrderChargeForPage(orderChargeDto);
    }

    /**
     * 根据订单ID查询订单详情
     */
    @GetMapping("queryOrderChargeItemByOrderId/{orderId}")
    @HystrixCommand
    public AjaxResult queryOrderChargeItemByOrderId(@PathVariable @Validated @NotBlank(message = "收费ID不能为空") String orderId) {
        return orderChargeService.selectOrderChargeItemByOrderId(orderId);
    }

    /**
     * 订单列表里再次支付宝支付
     */
    @GetMapping("toPayOrderWithZfb/{orderId}")
    @HystrixCommand
    public AjaxResult toPayOrderWithZfb(@PathVariable @Validated @NotBlank(message = "收费ID不能为空") String orderId) {
        OrderCharge orderCharge = orderChargeService.queryOrderChargeByOrderId(orderId);
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("【" + orderId + "】订单号所在的订单不存在，请核对后再输入");
        }
        if (orderCharge.getOrderStatus().equals(Constants.ORDER_STATUS_1)) {
            return AjaxResult.fail("【" + orderId + "】订单号不是未支付状态，请核对后再输入");
        }

        String outTradeNo = orderId;
        String subject = "医疗管理系统支付平台";
        String totalAmount = orderCharge.getOrderAmount().toString();
        String undiscountableAmount = null;
        String body = "";
        String notyifyUrl = AlipayConfig.notyifyUrl + outTradeNo;
        // 因为是支付宝支付，所以我们要返回给页面一个二维码
        Map<String, Object> pay = PayService.pay(outTradeNo, subject, totalAmount, undiscountableAmount, body, notyifyUrl);
        String qrCode = pay.get("qrCode").toString();
        if (StringUtils.isNotBlank(qrCode)) {
            // 创建支付成功
            HashMap<String, Object> map = new HashMap<>();
            map.put("orderId", outTradeNo);
            map.put("allAmount", totalAmount);
            map.put("payUrl", qrCode);
            return AjaxResult.success(map);
        } else {
            return AjaxResult.fail(pay.get("msg").toString());
        }
    }

    /**
     * 订单列表里再次现金支付
     */
    @GetMapping("payWithCash/{orderId}")
    @HystrixCommand
    public AjaxResult payWithCash(@PathVariable @Validated @NotBlank(message = "收费ID不能为空") String orderId) {
        OrderCharge orderCharge = orderChargeService.queryOrderChargeByOrderId(orderId);
        if (ObjectUtils.isEmpty(orderCharge)) {
            return AjaxResult.fail("【" + orderId + "】订单号所在的订单不存在，请核对后再输入");
        }
        if (orderCharge.getOrderStatus().equals(Constants.ORDER_STATUS_1)) {
            return AjaxResult.fail("【" + orderId + "】订单号不是未支付状态，请核对后再输入");
        }
        orderChargeService.paySuccess(orderId, Constants.PAY_TYPE_0, null);
        return AjaxResult.success();
    }


}

